import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
// 根据环境不同引入不同api地址
import { baseApi } from '@/config'

// create an axios instance
const service = axios.create({
  baseURL: baseApi, // url = base api url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true
      })
    }

    const defaultToken = ''
    const defaultAuthorization = ''
    // 登录
    config.headers['token'] = store.getters.token || defaultToken
    config.headers['authorization'] = store.getters.data || defaultAuthorization

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    if (res.status && res.status !== 200) {
      return Promise.reject(res || 'error')
    } else {
      const statusCode = [1003, 1004, 1002, 1001]
      const statusMap = {
        '1003': '请登录后再进行操作',
        '1004': '请登录后再进行操作',
        '1002': 'token过期',
        '1001': 'token无效'
      }

      // 登录超时,重新登录
      if (res.code === 2000) {
        // Toast.fail(res.msg)
      }

      if (statusCode.includes(res.code)) {
        Toast.fail(statusMap[res.code])
      }

      return Promise.resolve(res)
    }
  },
  error => {
    Toast.clear()
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
